export default {
  namespaced: true,
  state: {
    role: localStorage.getItem('role') || '',
    token: localStorage.getItem('token') || '',
    userInfo: localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : {},

    // 侧边导航菜单的数据
    menus: [
      {
        label: '图表',
        icon: 'Menu',
        path: '/dashBoard',
        roles: '*'
      },
      {
        label: '商品管理',
        icon: 'GoodsFilled',
        roles: ['admin', 'a', 'b'],
        children: [
          {
            label: '商品分类',
            path: '/cateList',
            roles: ['admin', 'a', 'b']
          },
          {
            label: '商品列表',
            path: '/itemList',
            roles: ['admin', 'a', 'b']
          }
        ]
      },
      {
        label: '个人中心',
        icon: 'User',
        path: '/userInfo',
        roles: ['admin', 'a', 'b']
      },
      {
        label: '设置',
        icon: 'Setting',
        path: '/setting',
        roles: ['a', 'b']
      }
    ]
  },

  // 相当于vuex中的计算属性
  getters: {
    authMenus (state) {
      const menus = JSON.parse(JSON.stringify(state.menus))
      const authMenus = []
      const role = localStorage.getItem('role')
      menus.forEach(menu => {
        // 过滤第一层导航
        if (menu.roles === '*' || menu.roles.includes(role)) {
          // 过滤子导航
          if (menu.children) {
            menu.children = menu.children.filter(subMenu => (subMenu.menu === '*' || subMenu.roles.includes(role)))
          }
          authMenus.push(menu)
        }
      })
      return authMenus
    }
  },

  mutations: {
    INIT_USER_INFO (state, { role, token, userInfo }) {
      state.role = role
      state.token = token
      state.userInfo = userInfo
    },

    USER_LOGOUT () {
      localStorage.removeItem('role')
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    }
  }
}
